<template>
	<div class="system-add-role-container">
		<el-dialog title="新增角色" v-model="state.isShowDialog" width="769px">
			<el-form :model="state.ruleForm" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色名称">
							<el-input v-model="state.ruleForm.name" placeholder="请输入角色名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色状态">
							<el-switch
								v-model="state.ruleForm.status"
								:active-value="1"
								:inactive-value="0"
								inline-prompt
								active-text="启"
								inactive-text="禁"
							></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序">
							<el-input-number v-model="state.ruleForm.sort" :min="0" :max="999" controls-position="right" placeholder="请输入排序" class="w100" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="角色描述">
							<el-input v-model="state.ruleForm.remark" type="textarea" placeholder="请输入角色描述" maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单权限">
							<el-tree
								ref="menuTreeRef"
								@check="checkMenuTree"
								:data="state.menuData"
								:default-checked-keys="state.defaultMenu"
								node-key="id"
								:props="{ children: 'children', label: 'name' }"
								show-checkbox
								class="menu-data-tree"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="接口权限">
							<el-tree
								ref="apiTreeRef"
								@check="checkApiTree"
								:props="{ children: 'children', label: 'name' }"
								:data="state.apiData"
								:default-checked-keys="state.defaultApi"
								node-key="id"
								show-checkbox
								class="menu-data-tree"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="关联用户">
							<div class="user-list" v-if="state.selUser.length">
								<span>{{ state.selUser.map((v) => v.username).join(',') }}</span>
							</div>
							<el-button type="primary" @click="onOpenUserDialog">选择用户</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="closeDialog" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<UserList ref="userListRef" :selUser="state.selUser" @handleSelectList="handleSelectList" />
	</div>
</template>

<script setup name="systemAddRole">
import UserList from './userList.vue';
import { editRole, getRoleDetail } from '@/api/system/role';
import { ElMessage } from 'element-plus';
import { find } from 'lodash';
import { nextTick } from 'vue';
const emits = defineEmits(['refresh']);
const props = defineProps({
	menuData: {
		type: Array,
	},
	apiData: {
		type: Array,
	},
});

const state = reactive({
	isShowDialog: false,
	ruleForm: {
		id: '',
		name: '', // 角色名称
		status: true, // 角色状态
		// roleSign: '', // 角色标识
		sort: 0, // 排序
		remark: '', // 角色描述
		permissions: '', //接口权限
		menus: '', //菜单权限
	},
	selUser: [], //选中的用户
	menuData: [],
	apiData: [],
	defaultApi: [], //默认选中接口
});
// 打开弹窗
const menuTreeRef = ref(null);
const apiTreeRef = ref(null);
const openDialog = async (row) => {
	// 获取菜单结构数据
	state.menuData = getMenuData(JSON.parse(JSON.stringify(props.menuData)));
	state.apiData = props.apiData;
	// 获取详情
	let res = await getRoleDetail({ id: row.id });
	if (res.code !== 0) return ElMessage.error(res.message);
	state.isShowDialog = true;
	state.ruleForm.id = row.id;
	state.ruleForm.name = res.data.name;
	state.ruleForm.status = res.data.status;
	state.ruleForm.sort = res.data.sort;
	state.ruleForm.remark = res.data.remark;
	state.defaultApi = res.data.permissions;
	state.selUser = res.data.adminers;
	// 回显菜单选中状态
	nextTick(() => {
		// console.log(menuTreeRef.value);
		menuTreeRef.value.setCheckedKeys([]);
		res.data.menus.forEach((i) => {
			let node = menuTreeRef.value.getNode(i);
			if (node.isLeaf) {
				//如果是子节点，就把状态设置成选中
				menuTreeRef.value.setChecked(node, true);
			}
		});
	});
	state.ruleForm.permissions = state.defaultApi.join(',');
	state.ruleForm.menus = res.data.menus.join(',');
	// console.log(state.ruleForm.menus);
};

// 获取全部菜单
const getMenuData = (routes) => {
	const arr = [];
	routes.map((val) => {
		val['name'] = val.meta.title;
		arr.push({ ...val });
		if (val.children.length) getMenuData(val.children);
	});
	return arr;
};

const checkMenuTree = (e, a) => {
	let checkedMenus = menuTreeRef.value.getCheckedKeys();
	let hafCheckedMenus = menuTreeRef.value.getHalfCheckedKeys();
	let menus = [...checkedMenus, ...hafCheckedMenus];
	state.ruleForm.menus = menus.join(',');
};
const checkApiTree = (e, a) => {
	let permissions = a.checkedNodes
		.filter((v) => v.type === 1)
		.map((v) => v.id)
		.join(',');
	state.ruleForm.permissions = permissions;
};

//选中的用户
const handleSelectList = (val) => {
	state.selUser = val;
};

// 打开用户选择弹窗
const userListRef = ref(null);
const onOpenUserDialog = () => {
	userListRef.value.openDialog(state.selUser);
};

// 关闭弹窗
const closeDialog = () => {
	state.isShowDialog = false;
};

// 修改
const onSubmit = async () => {
	// 设置接口数据
	state.ruleForm.users = state.selUser.map((v) => v.id).join(',');
	let res = await editRole(state.ruleForm);
	if (res.code === 0) {
		ElMessage.success(res.message);
		closeDialog();
		emits('refresh');
		state.defaultMenu = [];
		state.defaultApi = [];
	} else {
		ElMessage.error(res.message);
	}
};

onMounted(() => {
	//  先清空选中状态
	// menuTreeRef.value.setCheckedKeys([]);
	// functionIdList.forEach((i) => {
	// 	// 根据id 拿到 Tree 组件中的node的所有信息
	// 	let node = this.$refs.tree.getNode(i);
	// 	// node.isLeaf：判断当前节点是否为子节点
	// 	if (node.isLeaf) {
	// 		//如果是子节点，就把状态设置成选中
	// 		this.$refs.tree.setChecked(node, true);
	// 	} else {
	// 	}
	// });
	//functionIdList是设置选中的数据
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.system-add-role-container {
	.menu-data-tree {
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
		padding: 5px;
	}
	.user-list {
		max-width: 520px;
		margin-right: 15px;
		padding: 0 10px;
		border: 1px solid var(--el-border-color);
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
	}
}
</style>
